import os
import shutil
import sys
import subprocess
import datetime
from git import Repo
from ftplib import FTP

branch=''

branch=os.environ["Branch_Name"]
print(f"branch: {branch}")



# print("------------begin build----------------")
# command = 'npm config -g set registry http://nexus.supcon.com/repository/npm-proxy/'
# command1 = 'yarn config set electron_mirror http://nexus.supcon.com/repository/electron-proxy-raw/'
# command2 = 'yarn config set electron_builder_binaries_mirror http://nexus.supcon.com/repository/electron-builder-proxy-raw/'
# command3 = 'yarn && yarn packWeb'

# subprocess.run(command, shell=True)
# subprocess.run(command1, shell=True)
# subprocess.run(command2, shell=True)
# subprocess.run(command3, shell=True)

# print("------------end build----------------")

print("------------begin copyfiles----------------")

repo_path = r'./'
output_file= f'../pid_exe/build/version_frontend.log'

source_folder = r"./packages/web/build"
target_folder = r"../pid_exe/build/files/nginx/html/pid"

# 清空目标文件夹
if os.path.exists(target_folder):
    shutil.rmtree(target_folder)

# 创建目标文件夹
os.makedirs(target_folder)

# 复制文件
# 递归复制文件夹和文件
for root, dirs, files in os.walk(source_folder):
    relative_path = os.path.relpath(root, source_folder)
    target_dir = os.path.join(target_folder, relative_path)
    os.makedirs(target_dir, exist_ok=True)
    
    for file in files:
        source_path = os.path.join(root, file)
        target_path = os.path.join(target_dir, file)
        shutil.copy2(source_path, target_path)
        
print("------------end copyfiles----------------")

print("------------begin create log----------------")
date_format = "%Y%m%d%H%M%S"
TIME =datetime.datetime.now().strftime(date_format)

def save_commits_to_file(repo_path, num_commits, output_file,version,branch):
    repo = Repo(repo_path)
    commits = list(repo.iter_commits(branch, max_count=num_commits))

    with open(output_file, 'w') as file:
        file.write(f"build date: {version}\n\nbranch:{branch}\n\n")
        for commit in commits:
            file.write(f"Date: {commit.authored_datetime}\n")
            file.write(f"Author: {commit.author.name} <{commit.author.email}>\n")
            file.write(f"Commit ID: {commit.hexsha}\n")
            file.write(f"Message: {commit.message}\n\n\n")

    print(f"commites save to file: {output_file}")


save_commits_to_file(repo_path, 10, output_file,TIME,branch)

print("------------end create log----------------")


print("------------upload to ftp----------------")

def upload_folder_to_ftp(source_path, target_folder, ftp_host, ftp_user, ftp_password):
    # 连接到FTP服务器
    ftp = FTP(ftp_host)
    ftp.set_debuglevel(1) #打开调试级别2，显示详细信息
    ftp.login(user=ftp_user, passwd=ftp_password)
    print(ftp.getwelcome()) #打印出欢迎信息

    def create_remote_directory(remote_path):
        # 递归创建远程目录
        if remote_path:
            try:
                ftp.cwd(remote_path)  # 尝试切换到目录
            except:
                parent_path, current_dir = os.path.split(remote_path)
                create_remote_directory(parent_path)  # 递归创建父目录
                ftp.mkd(remote_path)  # 创建当前目录
                ftp.cwd(remote_path)  # 切换到当前目录

    # 获取源路径的基本目录名
    base_folder = os.path.basename(source_path)
    if os.path.isfile(source_path):  # 如果是文件
        create_remote_directory(target_folder)  # 创建远程目录
        ftp.cwd(target_folder)  # 尝试切换到目录
        basefile=os.path.basename(source_path)
        with open(source_path, 'rb') as file:
            ftp.storbinary(f'STOR {basefile}', file)
            print(f"file {basefile} upload success")

    # 遍历源路径下的所有子文件夹和文件
    for root, dirs, files in os.walk(source_path):
        relative_path = os.path.relpath(root, source_path)
        remote_path = os.path.join(target_folder, base_folder, relative_path)
        create_remote_directory(remote_path)  # 创建远程目录

        for file_name in files:
            local_file = os.path.join(root, file_name)
            remote_file = os.path.join(remote_path, file_name)
            with open(local_file, 'rb') as file:
                ftp.storbinary(f'STOR {remote_file}', file)  # 上传文件
                print(f"file {local_file} upload success")

    # 关闭FTP连接
    ftp.quit()

date_format = "%Y%m%d%H%M%S"
TIME =datetime.datetime.now().strftime(date_format)
repo_path = r'./'
server = "10.30.71.68"
username = "user"
password = "12345"
remote_folder = "/pid4/"+TIME+"_"+branch.replace("origin", "").replace("/", "").replace("\\", "")
#以下为zxb注释
upload_folder_to_ftp(source_path=r"./packages/web/build",target_folder=remote_folder,ftp_host=server,ftp_user=username,ftp_password=password)
upload_folder_to_ftp(source_path=output_file,target_folder=remote_folder,ftp_host=server,ftp_user=username,ftp_password=password)

print("------------upload to ftp----------------")